package cn.kgc.vue.controller;

import cn.hutool.core.util.IdUtil;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.entity.Template;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.service.TemplateService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/10/8
 * @description
 */
@RestController
@RequestMapping("template")
public class TemplateController {


    @Resource
    private TemplateService templateService;

    @PostMapping("page")
    public ResponseResult templatePage(@RequestBody QueryCondition<Template> queryCondition) {
        return templateService.templatePage(queryCondition);
    }

    // 添加资源信息
    @PostMapping("add")
    public ResponseResult addTemplateInfo(@RequestBody Template template){
        templateService.save(template);
        return ResponseResult.success();
    }

    // 上传资源
    @PostMapping("upload")
    public ResponseResult uploadTemplate(MultipartFile file) {

        if (file.isEmpty()) {
            return ResponseResult.fail().message("请选择文件");
        }

        // 处理文件名   唯一
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuid = IdUtil.simpleUUID();
        String uuidName = uuid+"."+filenameExtension;
        // 获取文件大小
        double size = file.getSize()/1024.0;

        // 文件上传
        File f = new File("D:\\upload\\springboot\\" + uuidName);
        try {
            file.transferTo(f);
            return  ResponseResult.success()
                    .data("size",size)
                    .data("uuidName",uuidName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    // 删除资源
    @DeleteMapping("delete/{uuidName}")
    public ResponseResult deleteTemplate(@PathVariable("uuidName") String uuidName){

       return templateService.deleteTemplate(uuidName);
    }


    // 资源下载
    @PostMapping("download")
    public void downloadTemplate(@RequestBody Map<String,String> params, HttpServletResponse response){

        String uuid = params.get("uuid");
        File file = new File("D:\\upload\\springboot\\" + uuid);

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
